<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="title">云图书馆</div>
      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="登录" name="login">
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            label-position="top"
          >
            <template v-if="loginType === 'password'">
              <el-form-item prop="username" label="用户名/邮箱">
                <el-input
                  v-model="loginForm.username"
                  placeholder="请输入用户名或邮箱"
                  prefix-icon="User"
                />
              </el-form-item>
              <el-form-item prop="password" label="密码">
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="请输入密码"
                  prefix-icon="Lock"
                  show-password
                  @keyup.enter="handleLogin"
                />
              </el-form-item>
            </template>

            <template v-else>
              <el-form-item prop="email" label="邮箱">
                <el-input
                  v-model="loginForm.email"
                  placeholder="请输入邮箱"
                  prefix-icon="Message"
                />
              </el-form-item>
              <el-form-item prop="code" label="验证码">
                <el-input
                  v-model="loginForm.code"
                  placeholder="请输入验证码"
                  prefix-icon="Key"
                >
                  <template #append>
                    <el-button
                      :disabled="!!timer"
                      @click="handleSendLoginCode"
                    >
                      {{ timer ? `${countdown}s后重试` : '发送验证码' }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </template>

            <el-form-item>
              <el-radio-group v-model="loginType" class="login-type">
                <el-radio label="password">密码登录</el-radio>
                <el-radio label="email">验证码登录</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" class="submit-button" @click="handleLogin" :loading="loading">
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="注册" name="register">
          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            label-position="top"
          >
            <el-form-item prop="email" label="邮箱">
              <el-input
                v-model="registerForm.email"
                placeholder="请输入邮箱"
                prefix-icon="Message"
              />
            </el-form-item>
            <el-form-item prop="code" label="验证码">
              <el-input
                v-model="registerForm.code"
                placeholder="请输入验证码"
                prefix-icon="Key"
              >
                <template #append>
                  <el-button
                    :disabled="!!registerTimer"
                    @click="handleSendRegisterCode"
                  >
                    {{ registerTimer ? `${registerCountdown}s后重试` : '发送验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="username" label="用户名">
              <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="password" label="密码">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="submit-button" @click="handleRegister" :loading="loading">
                注册
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  sendRegisterCode,
  register,
  login,
  sendLoginCode,
  loginByEmail
} from '@/api/user'

const router = useRouter()
const loading = ref(false)
const activeTab = ref('login')
const loginType = ref('password')
const loginFormRef = ref(null)
const registerFormRef = ref(null)

// 倒计时相关
const timer = ref(null)
const registerTimer = ref(null)
const countdown = ref(0)
const registerCountdown = ref(0)

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  email: '',
  code: ''
})

// 注册表单
const registerForm = reactive({
  email: '',
  code: '',
  username: '',
  password: ''
})

// 表单验证规则
const validateEmail = (rule, value, callback) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!value) {
    callback(new Error('请输入邮箱'))
  } else if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'))
  } else {
    callback()
  }
}

const validateUsername = (rule, value, callback) => {
  const usernameRegex = /^[a-zA-Z0-9_]{2,20}$/
  if (!value) {
    callback(new Error('请输入用户名'))
  } else if (!usernameRegex.test(value)) {
    callback(new Error('用户名只能包含字母、数字、下划线，长度2-20位'))
  } else {
    callback()
  }
}

const validatePassword = (rule, value, callback) => {
  const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (!passwordRegex.test(value)) {
    callback(new Error('密码必须包含字母和数字，长度不少于6位'))
  } else {
    callback()
  }
}

const loginRules = {
  username: [{ required: true, message: '请输入用户名或邮箱', trigger: 'blur' }],
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }],
  email: [{ validator: validateEmail, trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const registerRules = {
  email: [{ required: true, validator: validateEmail, trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  username: [{ required: true, validator: validateUsername, trigger: 'blur' }],
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }]
}

// 开始倒计时
const startCountdown = (type) => {
  const timerRef = type === 'login' ? timer : registerTimer
  const countdownRef = type === 'login' ? countdown : registerCountdown
  
  countdownRef.value = 60
  timerRef.value = setInterval(() => {
    countdownRef.value--
    if (countdownRef.value <= 0) {
      clearInterval(timerRef.value)
      timerRef.value = null
    }
  }, 1000)
}

// 发送登录验证码
const handleSendLoginCode = async () => {
  try {
    await loginFormRef.value.validateField('email')
    await sendLoginCode({ email: loginForm.email })
    ElMessage.success('验证码已发送')
    startCountdown('login')
  } catch (error) {
    ElMessage.error(error.message || '发送失败')
  }
}

// 发送注册验证码
const handleSendRegisterCode = async () => {
  try {
    await registerFormRef.value.validateField('email')
    await sendRegisterCode(registerForm.email)
    ElMessage.success('验证码已发送')
    startCountdown('register')
  } catch (error) {
    ElMessage.error(error.message || '发送失败')
  }
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    let result
    if (loginType.value === 'password') {
      result = await login({
        username: loginForm.username,
        password: loginForm.password
      })
    } else {
      result = await loginByEmail({
        email: loginForm.email,
        code: loginForm.code
      })
    }
    
    localStorage.setItem('token', result.data.token)
    ElMessage.success('登录成功')
    router.push('/')
  } catch (error) {
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    loading.value = true
    
    await register(registerForm)
    ElMessage.success('注册成功')
    activeTab.value = 'login'
    registerFormRef.value.resetFields()
  } catch (error) {
    ElMessage.error(error.message || '注册失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 420px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 20px;
}

.login-tabs {
  margin-top: 20px;
}

.submit-button {
  width: 100%;
  margin-top: 10px;
}

.login-type {
  margin: 10px 0;
}

:deep(.el-tabs__nav) {
  width: 100%;
  display: flex;
}

:deep(.el-tabs__item) {
  flex: 1;
  text-align: center;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style> 